package cn.itsource.xhy.utils;

import cn.itsource.xhy.org.domain.Employee;
import cn.itsource.xhy.org.service.IEmployeeService;
import cn.itsource.xhy.user.domain.LoginInfo;
import cn.itsource.xhy.user.domain.User;
import cn.itsource.xhy.user.service.IUserService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.http.HttpServletRequest;

public class LoginContext {

    public static Object getObject(HttpServletRequest request){
        // 拿到请求中的token
        String token = request.getHeader("TOKEN");
        // 拿到spring容器
        WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(request.getServletContext());
        // 拿到RedisTemplate对象
        RedisTemplate redisTemplate = applicationContext.getBean("redisTemplate", RedisTemplate.class);
        // 拿到logininfo对象
        LoginInfo loginInfo = (LoginInfo) redisTemplate.opsForValue().get(token);
        // 判断对象是用户还是前端人员
        if (loginInfo.getType() == 1){
            IUserService userService = applicationContext.getBean(IUserService.class);
            User user = userService.findById(loginInfo.getUId());
            // 返回对象
            return user;
        } else {
            IEmployeeService employeeService = applicationContext.getBean(IEmployeeService.class);
            Employee employee = employeeService.findById(loginInfo.getUId());
            // 返回对象
            return employee;
        }
    }
}
